"""
轮播图组件
支持自动播放、手动切换和指示点显示
"""

import tkinter as tk
from tkinter import ttk
from core.utils.logger import debug, info
from core.utils.image_utils import load_thumbnail


class Carousel(ttk.Frame):
    """轮播图组件"""
    
    def __init__(self, parent, items=None, auto_play=True, interval=4000, on_click=None):
        """
        初始化轮播图
        
        Args:
            parent: 父容器
            items: 轮播图项目列表，每个项目包含 {image_path, title, subtitle, action}
            auto_play: 是否自动播放
            interval: 自动播放间隔（毫秒）
            on_click: 点击回调函数
        """
        super().__init__(parent)
        
        self.items = items or []
        self.auto_play = auto_play
        self.interval = interval
        self.on_click = on_click
        self.current_index = 0
        
        # UI组件
        self.canvas = None
        self.indicator_frame = None
        self.indicators = []
        
        # 定时器
        self.auto_play_timer = None
        
        # 创建UI
        self._create_widgets()
        
        # 开始自动播放
        if self.auto_play and len(self.items) > 1:
            self.start_auto_play()
    
    def _create_widgets(self):
        """创建UI组件"""
        # 主容器
        main_frame = ttk.Frame(self)
        main_frame.pack(fill='both', expand=True)
        
        # 轮播图区域
        self.carousel_frame = ttk.Frame(main_frame, relief='raised', borderwidth=2)
        self.carousel_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 使用Canvas创建轮播图
        self.canvas = tk.Canvas(
            self.carousel_frame,
            highlightthickness=0,
            bg='#F5F5F5'
        )
        self.canvas.pack(fill='both', expand=True)
        
        # 左箭头按钮
        self.left_btn = ttk.Button(
            self.carousel_frame,
            text='◀',
            command=self.previous,
            width=3
        )
        self.left_btn.place(relx=0, rely=0.5, anchor='w', x=5, y=0)
        
        # 右箭头按钮
        self.right_btn = ttk.Button(
            self.carousel_frame,
            text='▶',
            command=self.next,
            width=3
        )
        self.right_btn.place(relx=1, rely=0.5, anchor='e', x=-5, y=0)
        
        # 指示器容器
        self.indicator_frame = ttk.Frame(main_frame)
        self.indicator_frame.pack(fill='x', pady=(0, 10))
        
        # 创建指示器
        self._create_indicators()
        
        # 绑定点击事件
        self.canvas.bind('<Button-1>', self._on_click)
        
        # 初始显示第一项
        if self.items:
            self.show_item(0)
    
    def _create_indicators(self):
        """创建指示点"""
        # 清除现有指示器
        for widget in self.indicator_frame.winfo_children():
            widget.destroy()
        
        self.indicators = []
        
        # 只为多个项目创建指示器
        if len(self.items) <= 1:
            return
        
        # 指示器居中
        container = ttk.Frame(self.indicator_frame)
        container.pack(anchor='center')
        
        for i in range(len(self.items)):
            indicator = ttk.Label(
                container,
                text='●',
                font=('Arial', 16),
                cursor='hand2'
            )
            indicator.pack(side='left', padx=3)
            indicator.bind('<Button-1>', lambda e, idx=i: self.show_item(idx))
            self.indicators.append(indicator)
        
        # 更新指示器状态
        self._update_indicators()
    
    def _update_indicators(self):
        """更新指示器状态"""
        for i, indicator in enumerate(self.indicators):
            if i == self.current_index:
                indicator.config(foreground='#FF6B35', font=('Arial', 16))
            else:
                indicator.config(foreground='#CCCCCC', font=('Arial', 16))
    
    def show_item(self, index):
        """显示指定索引的项目"""
        if not self.items or index < 0 or index >= len(self.items):
            return
        
        self.current_index = index
        
        # 获取当前项目
        item = self.items[index]
        
        # 清空画布
        self.canvas.delete('all')
        
        # 获取画布尺寸
        canvas_width = self.canvas.winfo_width() or 800
        canvas_height = self.canvas.winfo_height() or 200
        
        # 调整画布尺寸
        if canvas_width <= 1 or canvas_height <= 1:
            # 如果画布尚未渲染，设置默认尺寸
            canvas_width = 800
            canvas_height = 200
        
        # 绘制渐变背景
        for i in range(canvas_height):
            color_intensity = int(230 - (i / canvas_height) * 30)
            color = f'#{color_intensity:02X}{color_intensity:02X}{color_intensity:02X}'
            self.canvas.create_line(0, i, canvas_width, i, fill=color, width=1)
        
        # 加载并显示图片
        try:
            if item.get('image_path'):
                img = load_thumbnail(item['image_path'], size=(int(canvas_width * 0.6), canvas_height - 40))
                if img:
                    img_x = canvas_width // 2
                    img_y = canvas_height // 2
                    self.canvas.create_image(img_x, img_y, image=img, anchor='center')
                    self.canvas.image = img  # 保持引用
        except Exception as e:
            debug(f"加载轮播图图片失败: {e}")
        
        # 显示文字信息
        title = item.get('title', '')
        subtitle = item.get('subtitle', '')
        
        if title:
            self.canvas.create_text(
                canvas_width // 2,
                canvas_height // 2 - 30,
                text=title,
                font=('Arial', 24, 'bold'),
                fill='#2C3E50',
                anchor='center'
            )
        
        if subtitle:
            self.canvas.create_text(
                canvas_width // 2,
                canvas_height // 2 + 10,
                text=subtitle,
                font=('Arial', 14),
                fill='#7F8C8D',
                anchor='center'
            )
        
        # 更新指示器
        self._update_indicators()
        
        debug(f"显示轮播图项目 {index}: {title}")
    
    def _on_click(self, event):
        """点击事件处理"""
        if self.on_click and self.items:
            item = self.items[self.current_index]
            action = item.get('action')
            if action and callable(action):
                action()
    
    def next(self):
        """下一项"""
        if not self.items:
            return
        next_index = (self.current_index + 1) % len(self.items)
        self.show_item(next_index)
        
        # 重启自动播放
        if self.auto_play:
            self.restart_auto_play()
    
    def previous(self):
        """上一项"""
        if not self.items:
            return
        prev_index = (self.current_index - 1) % len(self.items)
        self.show_item(prev_index)
        
        # 重启自动播放
        if self.auto_play:
            self.restart_auto_play()
    
    def start_auto_play(self):
        """开始自动播放"""
        if not self.auto_play or len(self.items) <= 1:
            return
        
        self.stop_auto_play()
        self.auto_play_timer = self.after(self.interval, self._auto_play_step)
    
    def stop_auto_play(self):
        """停止自动播放"""
        if self.auto_play_timer:
            self.after_cancel(self.auto_play_timer)
            self.auto_play_timer = None
    
    def restart_auto_play(self):
        """重启自动播放"""
        self.stop_auto_play()
        self.start_auto_play()
    
    def _auto_play_step(self):
        """自动播放步骤"""
        if self.auto_play and len(self.items) > 1:
            self.next()
            self.start_auto_play()
    
    def set_items(self, items):
        """设置轮播图项目"""
        self.items = items
        self.current_index = 0
        self._create_indicators()
        if self.items:
            self.show_item(0)
        
        # 重新开始自动播放
        if self.auto_play and len(self.items) > 1:
            self.start_auto_play()
    
    def destroy(self):
        """销毁组件"""
        self.stop_auto_play()
        super().destroy()
